package com.example.sleepdebtcalculatorandroid;

import com.example.sleepdebtcalculatorandroid.R.id;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import android.widget.TextView;

public class CalculateSleepDebtActivity extends Activity implements View.OnClickListener {

	final Context context = this;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;
	private DatePicker datePickerStartRange;
	private DatePicker datePickerEndRange;
	private Dialog dialog;
	private TextView displayTextView;
	private NumberPicker numberPicker;
	private int idealSleepAmount;
	private int actualSleepAmount;
	private int numberOfDays;
	private  int sleepDebt;
	final private int HOURS_OR_MINUTES = 60;
	String[] idRange;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calculate_sleep_debt);
		dbHelper = new DatabaseHelper(this);
		db = dbHelper.getWritableDatabase();
		datePickerStartRange = (DatePicker)findViewById(id.datePickerStartRange);
		datePickerEndRange = (DatePicker)findViewById(id.datePickerEndRange);
		datePickerStartRange.setCalendarViewShown(false);
		datePickerEndRange.setCalendarViewShown(false);
		Button calculateSleepDebt = (Button)findViewById(id.calculateSleepDebtButton);
        calculateSleepDebt.setOnClickListener(this);
	}

	
	@Override
    public void onClick(View v) {
		dialog = new Dialog(context);        
	    dialog.setContentView(R.layout.dialog_calculate_sleep_debt);
        dialog.setTitle("       Erase Sleep Debt      ");
		displayTextView = (TextView)dialog.findViewById(id.displayCurrentSleepDebtTextView);
		NumberPicker numberPicker = (NumberPicker)dialog.findViewById(id.numberPicker1);
        numberPicker.setMaxValue(365);
        numberPicker.setMinValue(1);
        numberPicker.setValue(1);
        numberPicker.setWrapSelectorWheel(true);
        numberPicker.setDescendantFocusability(numberPicker.FOCUS_BLOCK_DESCENDANTS);
		idRange = new String[2];
        idealSleepAmount = getIdealSleepAmount();
        actualSleepAmount = getActualSleepAmount();
        numberOfDays = getNumberOfDays();
        sleepDebt = calculateSleepDebt(idealSleepAmount, actualSleepAmount, numberOfDays);
        displaySleepDebt(sleepDebt, displayTextView, null);
        Button eraseSleepDebtButton = (Button)dialog.findViewById(id.eraseSleepDebtButton);
        eraseSleepDebtButton.setOnClickListener(new View.OnClickListener() {		
		@Override
		public void onClick(View v) {
			int numberOfDaysToEraseDebt = (int)((NumberPicker)dialog.findViewById(id.numberPicker1)).getValue();
			int sleepPerNightToEraseDebt = sleepDebt/numberOfDaysToEraseDebt;
            displaySleepDebt(sleepDebt, displayTextView, "\nYou will need to sleep:\n" + ((sleepPerNightToEraseDebt + idealSleepAmount)/HOURS_OR_MINUTES) + " hours and " + ((sleepPerNightToEraseDebt + idealSleepAmount)%HOURS_OR_MINUTES) + " minutes per night\nOver the next " + numberOfDaysToEraseDebt + " days to erase your sleep debt!");		
		}
        });    
        dialog.show();    
    }
	
	private int getIdealSleepAmount() {
		int idealSleepAmountHours;
		int idealSleepAmountMinutes;
		String[] SELECT = {"id", "idealSleepAmountHours", "idealSleepAmountMinutes"};
		Cursor cursor = db.query("idealSleepAmount", SELECT, null, null, null, null, null);
		while(cursor.moveToNext()){
			idealSleepAmountHours = Integer.parseInt(cursor.getString((cursor.getColumnIndex("idealSleepAmountHours"))));
			idealSleepAmountMinutes = Integer.parseInt(cursor.getString((cursor.getColumnIndex("idealSleepAmountMinutes"))));
			return ((idealSleepAmountHours*HOURS_OR_MINUTES) + idealSleepAmountMinutes);
		}
		return 0;
	}
	
	private int getActualSleepAmount() {
		int actualSleepAmountHours = 0;
		int actualSleepAmountMinutes = 0;
		idRange[0] = getId(datePickerStartRange);
		idRange[1] = getId(datePickerEndRange);
		Cursor cursorFinal = db.rawQuery("SELECT * from actualSleepAmount where id>=?  and id<=?",idRange);
		while(cursorFinal.moveToNext()){
			actualSleepAmountHours += Integer.parseInt(cursorFinal.getString((cursorFinal.getColumnIndex("actualSleepAmountHours"))));
			actualSleepAmountMinutes += Integer.parseInt(cursorFinal.getString((cursorFinal.getColumnIndex("actualSleepAmountMinutes"))));
		}
		return((actualSleepAmountHours*60) + actualSleepAmountMinutes);
	}
	
	private String getId(DatePicker datePicker) {
		String id = new String("");
		String[] selectionArgsStart = {Integer.toString(datePicker.getDayOfMonth()), Integer.toString(datePicker.getMonth()), Integer.toString(datePicker.getYear())};
		Cursor cursor = db.rawQuery("SELECT id from actualSleepAmount where day=?  and month=? and year=?",selectionArgsStart);
		while(cursor.moveToNext())
			id = cursor.getString(cursor.getColumnIndex("id"));
		return id;
	}
	
	private int getNumberOfDays() {
		int includeStartDay = 1;
		int startDay = Integer.parseInt(idRange[0]);
		int endDay = Integer.parseInt(idRange[1]);
		int numberOfDays = (endDay-startDay)+includeStartDay;
		return numberOfDays;
	}
	
	private int calculateSleepDebt(int idealSleepAmount, int actualSleepAmout, int numberOfDays){
		int sleepDebt = (idealSleepAmount * numberOfDays) - actualSleepAmout;
		if (sleepDebt <=0)
			return 0;
		else
			return sleepDebt;
	}
	
	private void displaySleepDebt(int sleepDebt, TextView textView, String eraseSleepDebt){
		int hours = sleepDebt/HOURS_OR_MINUTES;
		int minutes = sleepDebt%HOURS_OR_MINUTES;
		String[] startDate = convertDateToString((DatePicker)findViewById(id.datePickerStartRange));
        String[] endDate = convertDateToString((DatePicker)findViewById(id.datePickerEndRange));
		if (sleepDebt == 0)
			textView.setText("0 hours and 0 minutes");
		else if(eraseSleepDebt == null)
			textView.setText("From: " + startDate[1] + " " + startDate[0] + ", " + startDate[2] + "\nTo:     " + endDate[1] + " " + endDate[0] + ", " + endDate[2] + "\nCurrent Sleep Debt Is: " +  hours + " Hours and " + minutes + " Minutes!");
		else
			textView.setText("From: " + startDate[1] + " " + startDate[0] + ", " + startDate[2] + "\nTo:      " + endDate[1] + " " + endDate[0] + ", " + endDate[2] + "\nCurrent Sleep Debt Is: " +  hours + " Hours and " + minutes + " Minutes!\n" + eraseSleepDebt);	
	}
	
	private String[] convertDateToString(DatePicker datePicker){
		String[] date = new String[3];
		date[0] = Integer.toString(datePicker.getDayOfMonth());
		date[2] = Integer.toString(datePicker.getYear());
		switch(datePicker.getMonth()){
			case 0: date[1] = "January";
			case 1: date[1] = "February";
			case 2: date[1] = "March";
			case 3: date[1] = "April";
			case 4: date[1] = "May";
			case 5: date[1] = "June";
			case 6: date[1] = "July";
			case 7: date[1] = "August";
			case 8: date[1] = "September";
			case 9: date[1] = "Octobember";
			case 10: date[1] = "November";
			case 11: date[1] = "December";
		}
		return date;
	}
}